package com.totem.base.filter;

import com.totem.base.CacheHolder;
import com.totem.base.SpringContextHolder;
import com.totem.base.constants.CacheConstants;
import com.totem.base.constants.CommonConstants;
import com.totem.base.constants.ErrorCode;
import com.totem.base.exception.BaseException;
import com.totem.base.mybatis.UserIdContext;
import com.totem.base.security.model.UsernamepasswordCertification;
import com.totem.base.util.FilterUtil;
import com.totem.base.util.RequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.servlet.HandlerExceptionResolver;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;
import java.util.Set;

@Slf4j
public class PermissionFilter extends OncePerRequestFilter {
    private ApplicationContext ctx;
    private CacheHolder cacheHolder;
    private HandlerExceptionResolver resolver;

    private static final AntPathMatcher ignoresMatch = new AntPathMatcher();
    private Set<String> ignores = Set.of(
            "/",
            "/swagger-ui.html",
            "/swagger-ui/",
            "/doc.html",
            "/favicon.ico",
            "/**/*.html",
            "/**/*.css",
            "/**/*.js",
            "/swagger-resources/**",
            "/v3/api-docs/**",
            "/admin/config/system",
            "/admin/code/verification",
            "/admin/code/verification/check",
            "/customer/create",
            "/customer/password/reset",
            "/customer/register/check",
            "/order/recharge",
            "/admin/test/**",
            "/admin/product/upload/file/**",
            "/admin/information/upload/file/**"
    );

    private static final AntPathMatcher accessMatch = new AntPathMatcher();
    private Set<String> financialCanAccessSet = Set.of(
            "/admin/firstPage",
            "/customer/page",
            "/order/recharge/page",
            "/order/withdraw/page",
            "/wallet/journal/page",
            "/wallet/collection/page",
            "/wallet/withdraw/payment",
            "/wallet/usdt/update"
    );

    private Set<String> operationCannotAccessSet = Set.of(
            "/wallet/withdraw/payment",
            "/wallet/usdt/update"
    );

    @Override
    protected void initFilterBean() throws ServletException {
        ctx = SpringContextHolder.getApplicationContext();
        resolver = ctx.getBean("handlerExceptionResolver", HandlerExceptionResolver.class);
        cacheHolder = ctx.getBean("cacheHolder", CacheHolder.class);
    }
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String contextPath = request.getContextPath();
        String requestUri = request.getRequestURI();
        String username = "";

        Long userId = UserIdContext.getUserId();
        if(userId==null || userId<=0){
            resolver.resolveException(request, response, null, new BaseException(ErrorCode.UNAUTHORIZED));
        }
        Object tokenObj = cacheHolder.get(CacheConstants.CACHE_TOKEN+userId);
        if(Objects.nonNull(tokenObj)){
            Object cachedObj = cacheHolder.get(CacheConstants.CACHE_CERT+tokenObj);
            if(cachedObj instanceof UsernamepasswordCertification) {
                UsernamepasswordCertification cert = (UsernamepasswordCertification) cachedObj;
                username = cert.getUsername();
            }
        }
        if(StringUtils.isNotBlank(username)){
            if(username.equalsIgnoreCase(CommonConstants.DEFAULT_FINANCIAL)){
                String accessUri = requestUri.substring(contextPath.length());
                boolean canAccess = financialCanAccessSet.stream().anyMatch(e->accessMatch.match(e, accessUri));
                if(!canAccess){
                    log.warn("financial 禁止访问[{}]", accessUri);
                    resolver.resolveException(request, response, null, new BaseException(ErrorCode.CANNOT_ACCESS));
                }
            }
            if(username.equalsIgnoreCase(CommonConstants.DEFAULT_OPERATION)){
                String accessUri = requestUri.substring(contextPath.length());
                boolean cannotAccess = operationCannotAccessSet.stream().anyMatch(e->accessMatch.match(e, accessUri));
                if(cannotAccess){
                    log.warn("operation 禁止访问[{}]", accessUri);
                    resolver.resolveException(request, response, null, new BaseException(ErrorCode.CANNOT_ACCESS));
                }
            }
        }
    }

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
        if(FilterUtil.ignoreMethod(request)) return true;

        final String requestUri = RequestUtil.getRelativePath(request);
        return ignores.stream().anyMatch(e->ignoresMatch.match(e, requestUri));
    }
}
